package pl.softech.server;

import java.nio.charset.Charset;
import java.util.Queue;
import java.util.logging.Level;
import java.util.logging.Logger;

import pl.softech.logger.MyLogger;

public class Worker implements Runnable {

    protected Logger logger = MyLogger.getLogger(getClass());
    
    private static int count = 0;

    private int num;

    private final WorkerManager manager;
    private final IRequestProcessor requestProcessor;

    public Worker(WorkerManager manager, IRequestProcessor requestProcessor) {
        this.manager = manager;
        this.requestProcessor = requestProcessor;
        num = count++;
    }

    public String getName() {
        return "Worker[" + num + "]";
    }

    @Override
    public void run() {
        Queue<Request> queue = manager.getRequestQueue();
        Request request;
        while (true) {

            synchronized (queue) {
                while (queue.isEmpty()) {
                    try {
                        queue.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                request = (Request) queue.poll();
            }

            IResponse response = requestProcessor.processRequest(request);
            logger.logp(Level.FINEST, Worker.class.getName(), "run", "Response:\n"+new String(response.getRawData()), Charset.defaultCharset());
            manager.sendData(request.getSocket(), response);
        }

    }

}
